<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use app\admin\model\ThemeModel;
use think\Db;
use think\View;

class HomeBaseController extends BaseController
{
    public $base; 
    public $path;
    public $r_url;
    public $base_url;

    public function _initialize()
    {
        $base_url = $this->base_url = "http://".$_SERVER['HTTP_HOST']."/";
        $base = $this->base = "http://".$_SERVER['HTTP_HOST']."/upload/home/";
        $path = $this->path = $_SERVER['DOCUMENT_ROOT']."/upload/home/";
        $r_url = $this->r_url = "http://".$_SERVER['HTTP_HOST']."/user/register/doreg";
        // 监听home_init
        hook('home_init');
        parent::_initialize();
        $siteInfo = cmf_get_site_info();
        View::share('site_info', $siteInfo);
    }

    public function _initializeView()
    {
        $cmfThemePath    = config('cmf_theme_path');
        $cmfDefaultTheme = cmf_get_current_theme();

        $themePath = "{$cmfThemePath}{$cmfDefaultTheme}";

        $root = cmf_get_root();
        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "{$themePath}/");
        config('view_replace_str', $viewReplaceStr);

        $themeErrorTmpl = "{$themePath}/error.html";
        if (file_exists_case($themeErrorTmpl)) {
            config('dispatch_error_tmpl', $themeErrorTmpl);
        }

        $themeSuccessTmpl = "{$themePath}/success.html";
        if (file_exists_case($themeSuccessTmpl)) {
            config('dispatch_success_tmpl', $themeSuccessTmpl);
        }


    }

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array $vars 模板输出变量
     * @param array $replace 模板替换
     * @param array $config 模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $template = $this->parseTemplate($template);
        $more     = $this->getThemeFileMore($template);
        $this->assign('theme_vars', $more['vars']);
        $this->assign('theme_widgets', $more['widgets']);
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 自动定位模板文件
     * @access private
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate($template)
    {
        // 分析模板文件规则
        $request = $this->request;
        // 获取视图根目录
        if (strpos($template, '@')) {
            // 跨模块调用
            list($module, $template) = explode('@', $template);
        }

        $viewBase = config('template.view_base');

        if ($viewBase) {
            // 基础视图目录
            $module = isset($module) ? $module : $request->module();
            $path   = $viewBase . ($module ? $module . DS : '');
        } else {
            $path = isset($module) ? APP_PATH . $module . DS . 'view' . DS : config('template.view_path');
        }

        $depr = config('template.view_depr');
        if (0 !== strpos($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = cmf_parse_name($request->controller());
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    $template = str_replace('.', DS, $controller) . $depr . cmf_parse_name($request->action(true));
                } elseif (false === strpos($template, $depr)) {
                    $template = str_replace('.', DS, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
        return $path . ltrim($template, '/') . '.' . ltrim(config('template.view_suffix'), '.');
    }

    /**
     * 获取模板文件变量
     * @param string $file
     * @param string $theme
     * @return array
     */
    private function getThemeFileMore($file, $theme = "")
    {

        //TODO 增加缓存
        $theme = empty($theme) ? cmf_get_current_theme() : $theme;

        // 调试模式下自动更新模板
        if (APP_DEBUG) {
            $themeModel = new ThemeModel();
            $themeModel->updateTheme($theme);
        }

        $themePath = config('cmf_theme_path');
        $file      = str_replace('\\', '/', $file);
        $file      = str_replace('//', '/', $file);
        $file      = str_replace(['.html', '.php', $themePath . $theme . "/"], '', $file);

        $files = Db::name('theme_file')->field('more')->where(['theme' => $theme])->where(function ($query) use ($file) {
            $query->where(['is_public' => 1])->whereOr(['file' => $file]);
        })->select();

        $vars    = [];
        $widgets = [];
        foreach ($files as $file) {
            $oldMore = json_decode($file['more'], true);
            if (!empty($oldMore['vars'])) {
                foreach ($oldMore['vars'] as $varName => $var) {
                    $vars[$varName] = $var['value'];
                }
            }

            if (!empty($oldMore['widgets'])) {
                foreach ($oldMore['widgets'] as $widgetName => $widget) {

                    $widgetVars = [];
                    if (!empty($widget['vars'])) {
                        foreach ($widget['vars'] as $varName => $var) {
                            $widgetVars[$varName] = $var['value'];
                        }
                    }

                    $widget['vars']       = $widgetVars;
                    $widgets[$widgetName] = $widget;
                }
            }
        }

        return ['vars' => $vars, 'widgets' => $widgets];
    }

    public function checkUserLogin()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            if ($this->request->isAjax()) {
                $this->error("您尚未登录", cmf_url("user/Login/index"));
            } else {
                $this->redirect(cmf_url("user/Login/index"));
            }
        }
    }

    //发送验证码
    public function sendSmsCode($phone){
        $data = array();
        $code = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $smsConf = array(
            'key'   => '78c6072218752b5f6010093879005127',//您申请的APPKEY
            'mobile'    => $phone, //接受短信的用户手机号码
            'tpl_id'    => '91909 ', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>"#code#=$code" //您设置的模板变量，根据实际情况修改
        );
        // dump($smsConf);die;
        $ok = $this->smsRule($phone);
        if($ok == 1){
            $content = $this-> juhecurl($sendUrl,$smsConf,1); //请求发送短信 
            if($content){
                $result = json_decode($content,true);
                $error_code = $result['error_code'];
                if($error_code == 0){
                    $info = array(
                        'phone' => $phone,
                        'code' => $code,
                        'add_time' => time()
                    );
                    $res = Db::table('sms_code')->insert($info);
                    if($res){
                        //状态为0，说明短信发送成功
                        $data['code'] = '200';
                        $data['msg'] = 'success';
                        $data['content'] = (object)$a=array();
                    }else{
                       $data['code'] = '400'; 
                       $data['msg'] = '验证码发送失败';
                       $data['content'] = (object)$a=array();
                    }
                }else{
                    //状态非0，说明失败
                    $data['code'] = '400';
                    $data['msg'] = "错误代码(".$error_code.")：".$result['reason'];
                    $data['content'] =(object)$a=array();
                }
            }else{
                //返回内容异常，以下可根据业务逻辑自行修改
                $data['code'] = '400';
                $data['msg'] = '验证码发送失败';
                $data['content'] = (object)$a=array();
            }
        }else{
            $data['code'] = '400';
            $data['msg'] = '验证码发送过于频繁';
            $data['content'] = (object)$a=array();        
        }
        return $data;
    } 

    //验证手机号
    public function checkphone($number){
        if(preg_match("/^1\d{10}$/",$number)){  
            return true;
        }else{  
            return false;
        } 
    } 

    //个人信息(基础的) 根据用户id
    public function userById($id){
        $user = Db::table("user")->where("id='$id'")->cache(60)->find();
        $card = Db::table('card')->field('is_ok')->where("user_id='$id'")->cache(60)->find(); 
        $user['card_ok'] = $card['is_ok'];
        return $user;
    } 

    //个人信息(基础的) 根据手机号
    public function userByPhone($user_phone){
        $user = Db::table("user")->where("user_phone='$user_phone'")->cache(60)->find(); 
        $id = $user['id'];
        $card = Db::table('card')->field('is_ok')->where("user_id='$id'")->cache(60)->find(); 
        $user['card_ok'] = $card['is_ok'];
        return $user;
    }    

    // //个人信息资金明细(基础的)
    // public function userMoney($id){
    //     $money = Db::table("money")->where("id='$id'")->cache(60)  ->find(); 
    //     return $money;
    // } 

    //每月个人明细(基础的)
    //@param  int $id 用户id
    public function monthMoney($id){
        //当前月份
        $month = date("Ym",time());
        // dump($month);die;
        $money = Db::table("user_money")->field("month_money,add_agent,add_shop,all_coin")->where("user_id='$id' and month='$month'")->cache(60)->find(); 
        // $money['month_money'] = $month_money;
        return $money;
    }     

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }  


    //table 表名称
    //user_id 用户id
    public function listById($table,$user_id){
        $info = Db::table($table)->where("user_id='$user_id'")->order('status desc')->select()->toArray();
        // dump($info);die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }    

    //新增
    //table 表名称
    //user_id 用户id
    //addData 要添加的信息
    public function addById($table,$user_id,$addData){
        $info = Db::table($table)->insert($addData);
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    } 

    //编辑单个收获地址
    //user_id 用户id
    //action_id业务表id
    //editData 修改的信息
    public function editById($table,$user_id,$action_id,$editData){
        $info = Db::table($table)->where("user_id='$user_id' and id='$action_id'")->update($editData);
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }  

    //table 表名称
    //where  限制条件
    //$items 查询字段
    public function selectTable($table,$where,$items='*'){
        $info = Db::table($table)->field($items)->where($where)->select()->toArray();
        // dump(Db::table($table)->getLastSql());die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }  

    //table 表名称
    //where  限制条件
    //items 查询字段
    public function findTable($table,$where,$items='*'){
        $info = Db::table($table)->field($items)->where($where)->find();
        // dump($info);die;
        // dump(Db::table($table)->getLastSql());die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }    

    //table 表名称
    //where  限制条件
    //
    public function deleteTable($table,$where){
        $info = Db::table($table)->where($where)->delete();
        // dump($info);die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }   

    //table 表名称
    //data  添加的数据
    //
    public function insertTable($table,$data){
        $info = Db::table($table)->insert($data);
        // dump($info);die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }

    //table 表名称
    //where  限制条件
    //
    public function editTable($table,$where,$data){
        $info = Db::table($table)->where($where)->update($data);
        // dump($info);die;
        if($info){
            $res = $info;
        }else{
            $res = $info; //无系统信息
        }
        return $res;
    }

    //base64编码转图片
    public function base64_image_content($base64_image_content)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $path = $this->path;
            // dump($path);die;
            $type = $result[2];
            $new_file1 = $path;
            if (!file_exists($new_file1)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file1, 0755);
            }
            $name = date('YmdHis') . mt_rand(0,99999999999999);
            $new_file = $name . ".{$type}";
            $new_file2 = $new_file1 . $new_file;
            // echo $new_file2;die;
            if (file_put_contents($new_file2, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                //不能超过20M
                if(filesize($path.$new_file)/1000>20000){
                    unlink($path.$new_file);
                }else{
                    return $new_file;
                }
            } else {
                return 0;
            }
        } else {
            return 0;
        }
        // dump('1');die;
    }


    //判断为ios客户端
    public function isJson($post){
        // dump($post);die;
        if(isset($post['jsonData'])){
            // dump($post);die;
            if(isset($post['s'])){
                unset($post['s']);
            }
            $post = json_decode($post['jsonData'],true);
            // dump($post);die;
        }else{
            // echo 1;
            if(isset($post['s'])){
                unset($post['s']);
            }
        }

        return $post;
    }  

    //代理商本月收益
    //user_id 查询的用户user_id
    public function agentMonthMoney($user_id,$machine_type,$month=0){
        $res = array();
        if($month == '0'){
            $month =(int)date('Ym');
        }else{
            $month = (int)$month;
        }
        //查询当前代理的信息
        $ok = $this->addMonthMoney($user_id,$machine_type,$month);
        // echo $ok;die;
        if($ok == 1){
            $agentWhere = "m.user_id='$user_id' and u.id='$user_id' and machine_type='$machine_type'";
            $agent = Db::table(['user'=>'u','user_money'=>'m'])->field('u.id,u.user_name,u.user_level,m.month_money,m.all_profit,balance_point')->where($agentWhere)->order("month desc")->limit(2)->select()->toArray();
            // dump($agent);die;
            if($agent){
                if(count($agent) == 1){
                    $res = $agent[0];
                }else{
                    $res = $agent[0];
                    $res['month_money'] = $agent[0]['month_money'] - $agent[1]['month_money'];
                    $res['all_profit'] = $agent[0]['all_profit'] - $agent[1]['all_profit'];
                    $res['point'] = $agent[1]['balance_point'];
                }
                // dump($res);die;
            }else{
                $res = array();
            } 
        }else{
            $res = array();
        }
        return $res;     
    }  

    //添加当月交易信息
    //user_id 
    public function addMonthMoney($user_id,$machine_type=0,$month=0){
        $res = array();
        if($month == '0'){
            $month =(int)date('Ym');
        }else{
            $month = (int)$month;
        }     
        $info = Db::table("user_money")->field("user_id,month,month_money,add_agent,add_shop,all_profit,all_coin,agent_level,teach_level,machine_num")->where("user_id='$user_id' and machine_type='$machine_type'")->order("month desc")->limit(1)->select()->toArray();
        $auth_id = $this->getAuthId($user_id);
        // if(!isset($machine_type)){
        //     $machine_type = 0;
        // }
        if($machine_type == '0'){
            $balance_point = 0.0006;
        }else{
            $balance_point = 0.0003;
        }
        //判断有无数据
        if($info){
            //判断是否有本月数据
            if($info[0]['month'] != $month){
                //无本月数据需要添加
                $addData = array(
                    'user_id' => $user_id,
                    'auth_id' => $auth_id,
                    'month_money' => $info[0]['month_money'],
                    'month_pos_profit' => 0,
                    'month_direct_profit' => 0,
                    'month_teach_profit' => 0,
                    'month_train_profit' => 0,
                    'add_agent' => $info[0]['add_agent'],
                    'add_shop' => $info[0]['add_shop'],
                    'month' => $month,
                    'month_quick_money' => 0,
                    'month_normal_money' => 0,
                    'month_yquick_money' => 0,
                    'all_profit' =>$info[0]['all_profit'],
                    'balance_point' => $balance_point,
                    'all_coin' => $info[0]['all_coin'],
                    'agent_level' => $info[0]['agent_level'],
                    'teach_level' => $info[0]['teach_level'],
                    'machine_num' => $info[0]['machine_num'],
                    'month_quick_profit' => 0,
                    'month_normal_profit' => 0,
                    'month_yquick_profit' => 0,
                    'agent_return_num' => 0,
                    'agent_return_money' => 0,
                    'machine_type' => $machine_type,
                );
                $add = 1;
            }else{
                $add = 0;
                $res = 1;
            }
        }else{
            $addData = array(
                'user_id' => $user_id,
                'auth_id' => $auth_id,
                'month_money' => 0,
                'month_pos_profit' => 0,
                'month_direct_profit' => 0,
                'month_teach_profit' => 0,
                'month_train_profit' => 0,
                'add_agent' => 0,
                'add_shop' => 0,
                'month' => $month,
                'month_quick_money' => 0,
                'month_normal_money' => 0,
                'month_yquick_money' => 0,
                'all_profit' =>0,
                'balance_point' => $balance_point,
                'all_coin' => 0,
                'agent_level' => 0,
                'teach_level' => 0,
                'machine_num' => 0,
                'month_quick_profit' => 0,
                'month_normal_profit' => 0,
                'month_yquick_profit' => 0,
                'agent_return_num' => 0,
                'agent_return_money' => 0,   
                'machine_type' => $machine_type,             
            ); 
            $add = 1;         
        }
        // dump($add);die;
        if($add == 1){
           $addInfo = Db::table("user_money")->insert($addData); 
        }else{
            $addInfo = 1;
        }       
        if($addInfo){
            $res = 1;
        }else{
            $res = 0;
        }
        return $res;
    }      

    //分页
    //$number 每页显示条数 $page页数
    public function pageAction($number,$page){
        $startPage = $page*$number;
        $stopPage  = $page*$number+$number;
        $limit = $startPage.','.$number; 
        return $limit;      
    }

    //短信限制规则 单条
    public function smsRuleOne($phone,$code){
        $info = Db::table("sms_code")->field('id,add_time')->where("phone='$phone' and code='$code' and is_ok=1")->order('add_time desc')->find();
        // dump($info);die;
        //删除24小时之前的数据
        $t = 3600*24;
        $delTime = time() - $t;
        if($info){
            if($info['add_time'] < $delTime){
                $id= $info['id'];
                Db::table("sms_code")->where("id='$id'")->delete();
                $res = 0;
            }else{
               $res = 1; 
            }
        }else{
            $res = 1;
        }
        return $res;
    }

    //修改已使用的验证码状态
    public function smsEditOne($phone,$code){
        $arr = array(
            'is_ok' => 0
        );
        $info = Db::table("sms_code")->where("phone='$phone' and code='$code' and is_ok=1")->update($arr);
        if($info){
            $res = 1;
        }else{
            $res = 0;
        }
        return $res;
    }    

    //短信限制规则
    public function smsRule($phone){
        //当前服务器时间
        $info = Db::table("sms_code")->field('id,add_time')->where("phone='$phone'")->order('add_time desc')->select()->toArray();
        //删除24小时之前的数据
        $t = 3600*24;
        // dump($info);die;
        if($info){
            $ok = 1;
            $ids = array();
            $delTime = time() - $t;
            $where = "phone='$phone' and add_time <".$delTime;
            $del = Db::table("sms_code")->field('id')->where($where)->order('add_time desc')->select()->toArray();
            // dump($del);die;
            if($del){
                foreach($del as $k=>$v){
                    $ids[$k] = $v['id'];
                }
                $ids = implode(",",$ids);
                // echo $ids;die;
                Db::table("sms_code")->where("id in ($ids)")->delete();
            }
            //每分钟只能一条
            $one = $info[0]['add_time']+60;
            if($one>time()){
                $ok = 0;
            }
            //10分钟3条
            if(isset($info[2]['add_time'])){
                $two = $info[2]['add_time']+600;
                if($two>time()){
                    $ok = 0;
                }
                // dump($two);dump(time());die;
            }            
            //一小时4次
            if(isset($info[3]['add_time'])){
                $two = $info[2]['add_time']+3600;
                if($two>time()){
                    $ok = 0;
                }
            }            
            //一天20次
            if(isset($info[3]['add_time'])){
                $two = $info[2]['add_time']+86400;
                if($two>time()){
                    $ok = 0;
                }
            }
                     
        }else{
            $ok = 1;//无短信数据 可直接发送短信
        }
        // dump($ok);die;
        return $ok;
    }

    public function register($post){
        $data = array();
        $phone = $post['user_phone'];
        $code = $post['code'];
        $register_code = $post['register_code'];        
        $result = Db::table("user")->where("user_phone='$phone'")->find();
        $smsRuleOne = $this->smsRuleOne($phone,$code);
        if($smsRuleOne == 1){
            $this->smsEditOne($phone,$code);
            $res = Db::table('sms_code')->where("phone='$phone' and code='$code'")->find();
            // dump($res);die;
            if(!$result){
                if($res){
                    $having = Db::table('user')->where("improt_code='$register_code'")->find();
                    if($having['is_have'] == '1'){
                        $auth_id = $having['id'];
                    }else{
                        $auth_id = $having['auth_id'];
                    }
                    //上级id
                    $parent_id = $having['id'];
                    if($having){
                        $info = array(
                            'auth_id' => $auth_id,
                            'parent_id' => $having['id'],
                            'path' => $having['path'].','.$having['id'],
                            'user_phone' => $post['user_phone'],
                            'register_code' => $post['register_code'],
                            'user_password' => md5($post['user_password']),
                            'phone_code' => $post['phone_code'],
                            'add_time' => time()
                        );                
                        $result = Db::table('user')->insert($info);
                        if($result){
                            //当前月份
                            $month = date("Ym",time());                        
                            $monthInfo = Db::table('user_money')->field("add_agent")->where("month='$month' and user_id='$parent_id'")->find();
                            // dump($monthInfo);die;
                            //给上级代理商累计其下代理商数量
                            if($monthInfo){
                                $add_agent = array('add_agent' => $monthInfo['add_agent']+1);
                                $money = Db::table('user_money')->where("month='$month' and user_id='$parent_id'")->update($add_agent);
                                if($money){
                                    $userInfo = Db::table("user")->field("id")->where("user_phone='$phone'")->find(); 
                                    // $data['content']['userinfo'] = $userInfo;
                                    $this->addMonthMoney($userInfo['id']);
                                    $data['code'] = '200'; 
                                    $data['msg'] = '注册成功'; 
                                    $data['content'] = (object)$a=array();
                                }else{
                                    $data['code'] = '402'; 
                                    $data['msg'] = '注册成功';   
                                    $data['content'] = (object)$a=array();
                                }                  
                            }else{
                                $add_agent = array(
                                    'user_id' => $having['id'],
                                    'month' => $month,
                                    'add_agent' => 1,
                                );
                                // dump($add_agent);die;
                                $money = Db::table('user_money')->insert($add_agent);
                                if($money){
                                    // $this->deleteTable('sms_code',$where('phone'=>$phone));
                                    $data['code'] = '200'; 
                                    $data['msg'] = '注册成功'; 
                                    $data['content'] = (object)$a=array();                               
                                }else{
                                    $data['code'] = '402'; 
                                    $data['msg'] = '注册成功'; 
                                    $data['content'] = (object)$a=array();                               
                                }
                            }
                        }else{
                            $data['code'] = '400'; 
                            $data['msg'] = '注册失败'; 
                            $data['content'] = (object)$a=array();                    
                        }                    
                    }else{
                        $data['code'] = '401'; 
                        $data['msg'] = '推荐码输入有误';  
                        $data['content'] = (object)$a=array();                   
                    }
                }else{
                    $data['code'] = '400'; 
                    $data['msg'] = '验证码错误';  
                    $data['content'] = (object)$a=array();               
                }
            }else{
                $data['code'] = '400';
                $data['msg'] = '手机号已被注册';
                $data['content'] = (object)$a=array();                
            }
        }else{
            $data['code'] = '400'; 
            $data['msg'] = '验证码错误';  
            $data['content'] = (object)$a=array();             
        }
        return $data;
    }

    //获取用户auth_id
    public function getAuthId($user_id){
        $user_info = Db::table("user")->field("auth_id")->where("id='$user_id'")->find();
        if($user_info){
            $auth_id = $user_info['auth_id'];
        }else{
            $auth_id = 0;
        }
        return $auth_id;
    }   

    /**
     * APISTORE 获取数据
     * @param $url 接口地址
     * @param null $param 要发送的数据
     * @param bool $ispost 是否采用POST发送,默认GET
     * @return mixed
     */
    function APISTORE($url, $param = null, $ispost = false)
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $ispost ? $url : $url . '?' . http_build_query($param));
        //如果是https协议
        if (stripos($url, "https://") !== FALSE) {
            /**
             * 如果需要验证证书
             */
            if (SSL_VERIFYPEER) {
                //验证交换证书
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
                //检查SSL证书公用名是否存在，并且是否与提供的主机名匹配
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
                //设置实现协议为TLS1.0版本
                curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
                //根证书文件路径,相对路径和绝对路径均可,
                //推荐使用绝对路径;为了安全证书文件最好不要和应用代码放在一起;
                //用户请保持更新 使用https接口需要设置该证书文件为可信任根证书，
                //以最大限度满足安全性（使用信任任何证书的方式并不安全）。
                curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
            } /**
             * 如果不需要验证证书
             */
            else {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
                //CURL_SSLVERSION_TLSv1
                curl_setopt($curl, CURLOPT_SSLVERSION, 1);
            }
        }

        //USERAGENT
        curl_setopt($curl, CURLOPT_USERAGENT, 'APIStore');
        //超时时间
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 120);
        curl_setopt($curl, CURLOPT_TIMEOUT, 120);
        //通过POST方式提交
        if ($ispost) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //返回内容
        $callbcak = curl_exec($curl);
        //关闭,释放资源
        curl_close($curl);
        //返回内容JSON_DECODE
        return json_decode($callbcak, true);
    }  

    //月份
    public function isMonth($month){
        if($month == '0'){
            $month =(int)date('Ym');
            $mth = (int)$month;
        }else{
            $mth = date("Ym",strtotime($month.'01'));
        }
        return $mth;
    }      

}